<template>
  <!--答题考试记录详情信息页面-->
  <view class="answerDetails flex flex-column">
    <UserHead v-if="userHeadShow" :headInfo="headInfo"></UserHead>
    <NavHead v-if="navHeadShow" :headInfo="headInfo" :practiceType="practiceType" :navList="navList"
      :selectVal="selectVal" @navbarClick="changeList"></NavHead>
    <view class="content f_1  flex flex-column">
      <view class="title">练习名称</view>
      <view class="list-view is-btn">
        <view v-if="list.length !== 0">
          <view v-for="(item, index) in list" :key="item.id">
            <!--判断题-->
            <BooleanQuestion v-if="item.type === '0101'" :key="item.id" :item="item" :answerNumber="index + 1" disabled
              :isShowScore="practiceType != 2">
            </BooleanQuestion>
            <!--单选题-->
            <RadioQuestion v-if="item.type === '0201'" :key="item.id" :item="item" :answerNumber="index + 1" disabled
              :isShowScore="practiceType != 2">
            </RadioQuestion>
            <!--多选题-->
            <MultipleQuestion v-if="item.type === '0301'" :key="item.id" :item="item" :answerNumber="index + 1" disabled
              :isShowScore="practiceType != 2">
            </MultipleQuestion>
            <!--描述题-->
            <DescribeQuestion v-if="['si02', 'si02', 'si03', 'si04'].includes(item.type)" :key="item.id" :item="item"
              :answerNumber="index + 1" disabled></DescribeQuestion>
          </view>
        </view>
        <Empty v-else style="margin-top: 30%;"></Empty>
      </view>
    </view>
    <!--切换用户试卷-->
    <view class="btn-item flex">
      <text class="prev f_1" @click="prev">上一个</text>
      <text class="next f_1" @click="next">下一个</text>
    </view>
    <!--导航、回到顶部功能菜单-->
    <view class="nav-btn flex flex-column" v-if="list.length">
      <image src="https://qiniu-bjjrzy.bjjrzy.com/bjupi/practice/cognPractice/improve/answer/top.png" class="top"
        v-show="scrollTop > windowHeight / 2" @click="scrollToTop" />
      <image src="https://qiniu-bjjrzy.bjjrzy.com/bjupi/practice/cognPractice/improve/answer/nav.png" class="nav"
        @click="openAnswerNav" />
    </view>
    <AnswerNav :nav-list="list" :answer-data="answerData" :currentIndex="0" ref="AnswerNav"
      @navItemClick="navItemClick"></AnswerNav>
  </view>
</template>

<script>
import RadioQuestion from "@/improve/components/answer/question/RadioQuestion.vue";
import DescribeQuestion from "@/improve/components/answer/question/DescribeQuestion.vue";
import BooleanQuestion from "@/improve/components/answer/question/BooleanQuestion.vue";
import MultipleQuestion from "@/improve/components/answer/question/MultipleQuestion.vue";
import AnswerNav from "@/improve/components/answer/AnswerNav.vue";
import { getPracticeStudentCheckItemHistory, getPracticeStudentCheckHeader, pageUpgPracticeStudentByDate, listLcPracticeCountStudentItemById, getLcPracticeCountHeader, getJsPracticeCountLevelItem, getJsPracticeCountStudentNext, listJsPracticeStudentLevel, getJsPracticeCheckItem } from '@/improve/services'
import { formatTime } from "@/utils/PrjUtils";
import Navbar from "@/improve/components/Navbar.vue";
import Empty from "@/improve/components/common/Empty.vue";
import UserHead from "./head/UserHead.vue";
import NavHead from "./head/NavHead.vue";

export default {
  name: "answerDetail",
  components: { UserHead, NavHead, AnswerNav, MultipleQuestion, BooleanQuestion, DescribeQuestion, RadioQuestion, Navbar, Empty },
  data() {
    return {
      upgPracticeJoinIds: [],
      upgPracticeUuid: '',
      practiceType: "1",//练测类型
      levelList: [],
      list: [],
      // list: [
      //   {
      //     analysis: null,
      //     answer: "A",
      //     collectStatus: 0,
      //     correct: true,
      //     hasAnswer: true,
      //     hierarchy: "5691,5790,5845,5846,5861,",
      //     itemId: 17530,
      //     itemNo: 218,
      //     itemStruct: "全部>相关知识>维护设备及处理设备故障>维护井场环保设备>螺旋输送机油品的更换步骤",
      //     itemText: "螺旋输送机持续运转使用，每（ ）检查油位油质，油位不足及时补充。第一次使用（ ）后应更换一次润滑油。",
      //     itemTypeName: "单选题",
      //     itemUuid: "4c429e3ef0eb4787a1355cece6daf75c",
      //     scoreRule: null,
      //     selections: `[{"code":"A","context":"5天，300小时"},{"code":"B","context":"7天，300小时"},{"code":"C","context":"5天，500小时"},{"code":"D","context":"7天，500小时"}]`,
      //     structId: 5861,
      //     stuAnswer: "B",
      //     subjectId: 24,
      //     type: "0201",
      //   },
      //   {
      //     analysis: null,
      //     answer: "",
      //     collectStatus: 0,
      //     correct: true,
      //     hasAnswer: true,
      //     hierarchy: "5691,5790,5845,5846,5861,",
      //     itemId: 17530,
      //     itemNo: 218,
      //     itemStruct: "全部>相关知识>维护设备及处理设备故障>维护井场环保设备>螺旋输送机油品的更换步骤",
      //     itemText: "请回答描述题",
      //     itemTypeName: "多选题",
      //     itemUuid: "4c429e3ef0eb4787a1355cece6daf75c",
      //     scoreRule: null,
      //     selections: ``,
      //     structId: 5861,
      //     stuAnswer: "全部>相关知识>维护设备及处理设备故障>维护井场环保设备>螺旋输送机油品的更换步骤",
      //     subjectId: 24,
      //     type: "si02",

      //   },
      //   {
      //     analysis: null,
      //     answer: "A,B,C",
      //     collectStatus: 0,
      //     correct: false,
      //     hasAnswer: true,
      //     hierarchy: "5691,5790,5845,5846,5861,",
      //     itemId: 17530,
      //     itemNo: 218,
      //     itemStruct: "全部>相关知识>维护设备及处理设备故障>维护井场环保设备>螺旋输送机油品的更换步骤",
      //     itemText: "螺旋输送机持续运转使用，每（ ）检查油位油质，油位不足及时补充。第一次使用（ ）后应更换一次润滑油。",
      //     itemTypeName: "多选题",
      //     itemUuid: "4c429e3ef0eb4787a1355cece6daf75c",
      //     scoreRule: null,
      //     selections: `[{"code":"A","context":"5天，300小时"},{"code":"B","context":"7天，300小时"},{"code":"C","context":"5天，500小时"},{"code":"D","context":"7天，500小时"}]`,
      //     structId: 5861,
      //     stuAnswer: "A,B",
      //     subjectId: 24,
      //     type: "0301",

      //   },
      //   {
      //     analysis: null,
      //     answer: "A",
      //     collectStatus: 0,
      //     correct: true,
      //     hasAnswer: true,
      //     hierarchy: "5691,5790,5815,5816,5822,",
      //     itemId: 17320,
      //     itemNo: 8,
      //     itemStruct: "全部>相关知识>使用工具与操作井场环保设备>使用工具>千斤顶的分类",
      //     itemText: "液压千斤顶的液压油除了用于液压传动系统中作中间介质，起传递和转换能量作用，还在用时起着液压系统内各部件间的润滑、防腐、冷却、冲洗等作用。",
      //     itemTypeName: "判断题",
      //     itemUuid: "182805fe50424dcbb42d6f131644fb9a",
      //     scoreRule: null,
      //     selections: null,
      //     structId: 5822,
      //     stuAnswer: "A",
      //     subjectId: 24,
      //     type: "0101",
      //   },
      //   {
      //     analysis: null,
      //     answer: "A,B,C",
      //     collectStatus: 0,
      //     correct: null,
      //     hasAnswer: false,
      //     hierarchy: "5691,5790,5845,5846,5861,",
      //     itemId: 17530,
      //     itemNo: 218,
      //     itemStruct: "全部>相关知识>维护设备及处理设备故障>维护井场环保设备>螺旋输送机油品的更换步骤",
      //     itemText: "螺旋输送机持续运转使用，每（ ）检查油位油质，油位不足及时补充。第一次使用（ ）后应更换一次润滑油。",
      //     itemTypeName: "多选题",
      //     itemUuid: "4c429e3ef0eb4787a1355cece6daf75c",
      //     scoreRule: null,
      //     selections: `[{"code":"A","context":"5天，300小时"},{"code":"B","context":"7天，300小时"},{"code":"C","context":"5天，500小时"},{"code":"D","context":"7天，500小时"}]`,
      //     structId: 5861,
      //     stuAnswer: null,
      //     subjectId: 24,
      //     type: "0301",
      //   }

      // ],
      currentIndex: 0,
      scrollTop: 0, //滚动距离
      windowHeight: 0,
      checkUuid: '',
      headInfo: {
        correctRate: ''
      },
      checkIndex: 0,
      date: '',
      checkUuidList: [],
      levelUuid: '',
      studentId: '',
      selectVal: '',
      navList: [],
      joinUuid: '',
    }
  },
  computed: {
    userHeadShow() {
      return this.practiceType == '1' || this.practiceType == '4'
    },
    navHeadShow() {
      return this.practiceType == '2' || this.practiceType == '3'
    },
    answerData() {
      const obj = {
        total: 0, //总数
        isCollect: false, //是否收藏
        collectTotal: 0,//收藏个数
        successTotal: 0, //答对数量
        errorTotal: 0, //打错数量
      }
      if (this.list.length) {
        obj.successTotal = this.list.filter((item) => item?.correct)?.length
        obj.errorTotal = this.list.filter((item) => !item?.correct)?.length
        obj.collectTotal = this.list.filter((item) => !item?.isCollect)?.length
        obj.total = this.list.length
      }
      return obj
    }
  },
  created() {
    this.list.forEach((item) => {
      if (item.selections) {
        try {
          item.selections = JSON.parse(item.selections)
        } catch (e) {

        }
      }
    })
  },
  methods: {
    // 获取用户练习信息
    async getUserPracticeInfo() {
      const data = await getPracticeStudentCheckHeader({ checkUuid: this.checkUuid })
      this.headInfo = { ...data, answerTime: data.answerTime <= 0 || !data.answerTime ? '00:00:00' : formatTime(data.answerTime) }
    },
    // 获取checkUuidList
    getDailyStatistics() {
      pageUpgPracticeStudentByDate({ upgPracticeUuid: this.upgPracticeUuid, date: this.date, pageNo: 1, pageSize: 1 }).then(res => {
        this.checkUuidList = res.checkUuidList
      })
    },
    // 获取试题列表 - 每日一练
    async getPracticeList() {
      const data = await getPracticeStudentCheckItemHistory({ checkUuid: this.checkUuid })
      this.list = data.map(i => ({
        ...i,
        stuAnswer: i.stuAnswer ? i.stuAnswer : '未答题',
        score: i.score ? i.score : 0,
        stuScore: i.stuScore ? i.stuScore : 0,
        selections: JSON.parse(i.selections),
      }))
    },
    // 获取试题列表 - 在线练测
    listLcPracticeCountStudentItemById() {
      listLcPracticeCountStudentItemById({ upgPracticeJoinId: this.selectVal }).then(res => {
        const { items, ...head } = res
        this.headInfo = { ...this.headInfo, ...head }
        this.list = res.items.map(i => ({
          ...i,
          stuAnswer: i.stuAnswer ? i.stuAnswer : '未答题',
          score: i.score ? i.score : 0,
          stuScore: i.stuScore ? i.stuScore : 0,
          selections: JSON.parse(i.selections),
        }))
      })
    },
    // 获取竞赛关卡
    async listJsPracticeStudentLevel() {
      const res = await listJsPracticeStudentLevel({ upgPracticeUuid: this.upgPracticeUuid, studentId: this.studentId })
      this.navList = res
      this.selectVal = this.navList[0].levelUuid
    },
    // 切换用户 - 每日一练/练测/竞赛/有奖
    async getJsPracticeCountStudentNext(next) {
      const data = await getJsPracticeCountStudentNext({ upgPracticeUuid: this.upgPracticeUuid, studentId: this.studentId, next, date: this.date })
      if (this.practiceType == '3') {
        this.studentId = data
        this.getJsPracticeCountLevelItem()
      } else if (this.practiceType == '2') {
        this.navList = data ? data.split(',') : []
        this.selectVal = this.navList[0]
        this.getJsPracticeCountLevelItem()
      } else {
        this.joinUuid = data
        this.getJsPracticeCheckItem()
      }
    },
    // 切换用户 - 每日一练/有奖
    async getJsPracticeCheckItem() {
      const data = await getJsPracticeCheckItem({ joinUuid: this.joinUuid })
      const { items, ...head } = data
      this.headInfo = { ...this.headInfo, ...head, answerTime: data.answerTime <= 0 || !data.answerTime ? '00:00:00' : formatTime(data.answerTime) };
      this.list = data.items.map(i => ({
        ...i,
        stuAnswer: i.stuAnswer ? i.stuAnswer : '未答题',
        score: i.score ? i.score : 0,
        stuScore: i.stuScore ? i.stuScore : 0,
        selections: JSON.parse(i.selections),
      }))
    },
    // 获取试题列表 - 知识竞赛
    async getJsPracticeCountLevelItem(init = false) {
      if (init) {
        await this.listJsPracticeStudentLevel()
      }
      const data = await getJsPracticeCountLevelItem({ levelUuid: this.selectVal, studentId: this.studentId })
      const { items, ...head } = data
      this.headInfo = { ...this.headInfo, ...head, avgNum: data.answerTime <= 0 || !data.answerTime ? '00:00:00' : formatTime(data.answerTime) };
      this.list = data.items.map(i => ({
        ...i,
        stuAnswer: i.stuAnswer ? i.stuAnswer : '未答题',
        score: i.score ? i.score : 0,
        stuScore: i.stuScore ? i.stuScore : 0,
        selections: JSON.parse(i.selections),
      }))
    },
    //打开导航弹窗
    openAnswerNav() {
      this.$refs.AnswerNav.open();
    },
    //题目导航定位
    navItemClick(index) {
      if (index !== -1) {
        // 从数组中移除该元素
        const [targetElement] = this.list.splice(index, 1);
        // 将元素插入到数组的第一位
        this.list.splice(0, 0, targetElement);
        this.$refs.AnswerNav.close();
        this.scrollToTop()
      }
    },
    scrollToTop() {
      uni.pageScrollTo({
        scrollTop: 0,
        duration: 300
      });
    },
    //上一位
    prev() {
      this.getJsPracticeCountStudentNext(false)
      // if (this.practiceType == '1') {
      //   if (this.checkIndex <= 0) {
      //     uni.showToast({
      //       title: '已经是第一个了',
      //       icon: 'none'
      //     })
      //     return
      //   }
      //   this.checkIndex--
      //   this.checkUuid = this.checkUuidList[this.checkIndex]
      //   this.getPracticeList()
      // }
      // if (this.practiceType == '3') {
      //   this.getJsPracticeCountStudentNext(false)
      // }
    },
    //下一位
    next() {
      this.getJsPracticeCountStudentNext(true)
      // if (this.practiceType == '1') {
      //   if (this.checkIndex >= this.checkUuidList.length - 1) {
      //     uni.showToast({
      //       title: '已经是最后一个了',
      //       icon: 'none'
      //     })
      //     return
      //   }
      //   this.checkIndex++
      //   this.checkUuid = this.checkUuidList[this.checkIndex]
      //   this.getPracticeList()
      // }
      // if (this.practiceType == '3') {
      //   this.getJsPracticeCountStudentNext(true)
      // }
    },
    // 切换-在线练测
    changeList(val) {
      if (this.selectVal == val) return
      this.selectVal = val
      this.list = []
      if (this.practiceType == '2') {
        this.listLcPracticeCountStudentItemById()
      } else {
        this.getJsPracticeCountLevelItem()
      }
    }
  },
  onLoad(options) {
    this.upgPracticeUuid = options.upgPracticeUuid
    this.checkUuid = options.checkUuid
    this.checkIndex = options.checkIndex

    this.practiceType = options.practiceType

    this.studentId = options.studentId // 1 2 3 4
    this.joinUuid = options.joinUuid // 1 3 4

    if (this.practiceType == '1') {
      this.date = options.date ? options.date : ''
      // this.getPracticeList()
      // this.getUserPracticeInfo()
      // this.getDailyStatistics()
      this.getJsPracticeCheckItem()
    }
    if (this.practiceType == '2') {
      this.navList = options.upgPracticeJoinIds ? options.upgPracticeJoinIds.split(',') : []
      this.selectVal = this.navList[0]
      this.listLcPracticeCountStudentItemById()
    }
    if (this.practiceType == '3') {
      this.headInfo.correctRate = options.correctRate
      this.getJsPracticeCountLevelItem(true)
    }
    if (this.practiceType == '4') {
      this.getJsPracticeCheckItem()
    }
    uni.getSystemInfo({
      success: (res) => {
        this.windowHeight = res.windowHeight
      }
    })
  },
  onPageScroll(e) {
    this.scrollTop = e.scrollTop;
  }
}
</script>

<style scoped lang="scss">
.answerDetails {
  height: 100vh;
  width: 100vw;
  background-color: #FFFFFF;


  .line {
    width: 100%;
    background-color: #F5F5F5;
  }


  .content {
    background-color: #FFFFFF;
    border-top-left-radius: 24rpx;
    border-top-right-radius: 24rpx;
    position: relative;
    margin-top: -25px;
    padding-bottom: calc(env(safe-area-inset-bottom));


    .title {
      font-size: 16px;
      color: #333333;
      font-weight: bold;
      padding: 18px;
      border-bottom: solid 1px #F5F5F5;
    }

    .navbar {
      padding: 15px;
    }

    .is-btn {
      padding-bottom: calc(80px + env(safe-area-inset-bottom));
    }

    .list-view {
      background-color: #FFFFFF;
      padding-top: 1px;
      box-sizing: border-box;
    }
  }

  .btn-item {
    padding-top: 10px;
    padding-bottom: calc(10px + env(safe-area-inset-bottom));
    position: fixed;
    background-color: #FFFFFF;
    box-shadow: 1px 1px 4px 2px rgba(0, 0, 0, 0.12);
    bottom: 0;
    width: calc(100% - 40px);
    z-index: 99;
    padding-left: 20px;
    padding-right: 20px;


    .next,
    .prev {
      border-radius: 12px;
      text-align: center;
      height: 45px;
      line-height: 45px;
      font-size: 16px;
      box-shadow: 1px 1px 4px 2px rgba(0, 0, 0, 0.12);
    }

    .next {
      margin-left: 20px;
      background-color: #37B874;
      color: #FFFFFF;

    }

    .prev {
      margin-left: 20px;
      background-color: #FFFFFF;
      color: #37B874;
    }

  }

  .nav-btn {
    position: fixed;
    right: 0;
    bottom: 100px;

    image {
      width: 50px;
      height: 50px;
    }
  }
}
</style>